<template>
  <div class="login-container">
    <div class="login-form">
      <h2>用户登录</h2>
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <div class="input-group">
            <label for="userAccount">账号</label>
            <input
              type="text"
              id="userAccount"
              v-model="form.userAccount"
              @blur="validateUsername"
              placeholder="请输入账号"
              :disabled="isLoading"
            />
          </div>
          <span class="error-message" v-if="touched.userAccount && errors.userAccount">{{ errors.userAccount }}</span>
        </div>
        <div class="form-group">
          <div class="input-group">
            <label for="userPassword">密码</label>
            <input
              type="password"
              id="userPassword"
              v-model="form.userPassword"
              @blur="validatePassword"
              placeholder="请输入密码"
              :disabled="isLoading"
            />
          </div>
          <span class="error-message" v-if="touched.userPassword && errors.userPassword">{{ errors.userPassword }}</span>
        </div>
        <button type="submit" :disabled="!isFormValid || isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '../api/user'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'

const userStore = useUserStore()

// 自定义消息提示样式
const showMessage = (message, type) => {
  ElMessage({
    message,
    type,
    duration: 2000,
    customClass: 'custom-message'
  })
}

const router = useRouter()
const form = ref({
  userAccount: '',
  userPassword: ''
})

const errors = ref({
  userAccount: '',
  userPassword: ''
})

const touched = ref({
  userAccount: false,
  userPassword: false
})

const isLoading = ref(false)

const validateUsername = () => {
  touched.value.userAccount = true
  const userAccount = form.value.userAccount
  const usernameRegex = /^[a-zA-Z][a-zA-Z0-9]{5,11}$/
  
  if (!userAccount) {
    errors.value.userAccount = '请输入账号'
  } else if (!usernameRegex.test(userAccount)) {
    errors.value.userAccount = '账号必须以字母开头，长度为6-12位，只能包含字母和数字'
  } else {
    errors.value.userAccount = ''
  }
}

const validatePassword = () => {
  touched.value.userPassword = true
  const userPassword = form.value.userPassword
  const passwordRegex = /^[a-zA-Z0-9]{5,12}$/
  
  if (!userPassword) {
    errors.value.userPassword = '请输入密码'
  } else if (!passwordRegex.test(userPassword)) {
    errors.value.userPassword = '密码长度为5-12位，只能包含字母和数字'
  } else {
    errors.value.userPassword = ''
  }
}

const isFormValid = computed(() => {
  return !errors.value.userAccount && !errors.value.userPassword && form.value.userAccount && form.value.userPassword
})

const handleSubmit = async () => {
  validateUsername()
  validatePassword()
  
  if (isFormValid.value) {
    try {
      isLoading.value = true
      const response = await login(form.value.userAccount, form.value.userPassword)
      // 根据返回的code判断登录状态
      if (response.code === 200) {
        // 登录成功，保存用户信息到store
        userStore.setUserInfo({
          id: response.data.id,
          userRole: response.data.userRole
        })
        // 显示成功提示
        showMessage('登录成功', 'success')
        // 延迟跳转到首页，让用户看到成功提示
        setTimeout(() => {
          router.push('/')
        }, 1000)
      } else {
        // 登录失败，显示服务器返回的错误信息
        showMessage(response.data || '登录失败，请检查账号和密码', 'error')
      }
    } catch (error) {
      // 处理请求失败的情况
      console.error('登录失败:', error)
      showMessage('网络错误，请稍后重试', 'error')
    } finally {
      isLoading.value = false
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-form {
  background-color: rgba(255, 255, 255, 0.4);
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  backdrop-filter: blur(10px);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -60%);
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1.5rem;
  display: flex;
  flex-direction: column;
  position: relative;
}

.input-group {
  display: flex;
  align-items: center;
}

label {
  width: 50px;
  margin-right: 10px;
  color: #666;
  flex-shrink: 0;
}

input {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus {
  outline: none;
  border-color: #4a90e2;
}

.error-message {
  color: #e74c3c;
  font-size: 0.75rem;
  margin-left: 70px;
  line-height: 1.2;
  position: absolute;
  top: 100%;
  margin-top: 0.25rem;
}

button {
  width: 100%;
  padding: 0.75rem;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

button:hover {
  background-color: #357abd;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

:global(.custom-message) {
  font-size: 18px;
  padding: 15px 20px;
  min-width: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:global(.el-message__content) {
  text-align: center;
  font-size: 18px;
  line-height: 1.5;
}

:global(.el-message--success) {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

:global(.el-message--error) {
  background-color: #fef0f0;
  border-color: #fde2e2;
}
</style> 